package com.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.mapper.ChapterContentDao;
import com.book.mapper.ChapterDao;
import com.book.pojo.Chapter;
import com.book.pojo.ChapterContent;
import com.book.pojo.Records;
import com.book.mapper.RecordsDao;
import com.book.service.RecordsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cxy
 * @since 2023-10-16 11:59:51
 */
@Service
public class RecordsServiceImpl extends ServiceImpl<RecordsDao, Records> implements RecordsService {

    @Autowired
    private RecordsDao recordsDao;
    @Autowired
    private ChapterDao chapterDao;
    @Autowired
    private ChapterContentDao chapterContentDao;

    @Override
    public ChapterContent getHistory(Records records) {
        QueryWrapper<Records> rqw = new QueryWrapper<>();
        rqw.eq("reader_id",records.getReaderId())
                .eq("book_id",records.getBookId());
        Records one = recordsDao.selectOne(rqw);
        if(one==null){
            QueryWrapper<Chapter> cqw = new QueryWrapper<>();
            cqw.eq("book_id",records.getBookId());
            Chapter chapter = chapterDao.selectList(cqw).get(0);
            records.setChaperId(chapter.getId());
            records.setPage(1);
            recordsDao.insert(records);
        }else {
            recordsDao.updateById(records);
        }
        int pageCount = (records.getPage()-1)*400;
        Chapter chapter = chapterDao.selectById(records.getChaperId());
        String content = chapterContentDao.selectById(records.getChaperId()).getChapterContent();
        StringBuilder sb = new StringBuilder(content);
        String s = sb.substring(pageCount, pageCount + 400);
        ChapterContent chapterContent = new ChapterContent();
        chapterContent.setId(records.getChaperId());
        chapterContent.setChapterContent(s);
        chapterContent.setBookId(chapter.getBookId());
        chapterContent.setChaperName(chapter.getChaperName());
        return chapterContent;
    }

    @Override
    public List<Records> selectByReaderId(Long id) {
        QueryWrapper<Records> qw = new QueryWrapper<>();
        qw.eq("reader_id",id);
        return recordsDao.selectList(qw);
    }

}
